package com.baimawangzi.recovery.dao.impl;

import com.baimawangzi.recovery.bean.Goods;
import com.baimawangzi.recovery.dao.GoodsDao;
import com.baimawangzi.recovery.util.dbutil.BeanHandler;
import com.baimawangzi.recovery.util.dbutil.OnlyHandler;

import java.util.List;

public class GoodsDaoImpl extends BaseDaoImpl<Goods> implements GoodsDao {
    public GoodsDaoImpl() {
        clazz= Goods.class;
        init();
    }
    @Override
    public List<Goods> map(String sql, Object[] obj) {
        List<Goods> goods = queryRunner.query(sql, new BeanHandler<Goods>(clazz), obj);
        return goods;
    }
    @Override
    public List<Goods> findByLimit(int m, int n) {
        String sql="select g.id,g.goodname,c.catename ,g.price,u.username  from t_goods g left join t_user u on u.id = g.userid left join t_cate c on g.cateid = c.id limit ?,?";
        Object[] object= {m, n};
        List<Goods> goods = queryRunner.query(sql,new BeanHandler<>(Goods.class),object);
        return goods;
    }

    @Override
    public long getCount() {
        String sql="select count(*) totalSize from t_goods where ?=?";

        Object[] objects={1,1};
        List<Object> onlylist = queryRunner.query(sql, new OnlyHandler(), objects);
        return (long) onlylist.get(0);
    }

    @Override
    public int add(Goods goods) {
        String sql="insert into t_goods values (null,?,?,?,?);";
        Object[] obj={goods.getGoodname(), new CateDaoImpl().getId(goods.getCatename()),goods.getPrice(),new UserDaoImpl().getId(goods.getUsername())};
        return queryRunner.update(sql,obj);
    }

    @Override
    public int delete(int id) {
        String sql ="delete from t_goods where id=?";
        Object[] obj={id};
        return queryRunner.update(sql,obj);
    }

    @Override
    public Goods findById(int id) {
        String sql="select g.id,g.goodname,c.catename ,g.price,u.username  from t_goods g left join t_user u on u.id = g.userid left join t_cate c on g.cateid = c.id where g.id = ?";
        Object[] object= {id};
        Goods goods = queryRunner.query(sql,new BeanHandler<>(Goods.class),object).get(0);
        return goods;
    }

    @Override
    public int update(Goods goods) {
        //update t_goods set goodname='111',cateid=1,price=222.22,userid=2 where id=1;
        String sql="update t_goods set goodname=?,cateid=?,price=?,userid=? where id=?";
        Object[] object= {goods.getGoodname(),new CateDaoImpl().getId(goods.getCatename()),goods.getPrice(),new UserDaoImpl().getId(goods.getUsername()),goods.getId()};

        return queryRunner.update(sql,object);
    }

}
